import { Interceptor, InterceptorInterface, Action } from "routing-controllers";
import { ResultDataMiddlewares } from "./ResultDataMiddlewares";
import { Service,Inject } from "typedi";


// 全局拦截器，拦截controller在数据响应给前端，按照标准格式输出数据，同时session存储用户
@Service()
export class JsonResponseMiddlewares implements InterceptorInterface {

  @Inject()
  private resultDataMiddlewares: ResultDataMiddlewares
    
  intercept(action: Action, content: any) {
    try {
      if(content.length != 0 && !(content.hasOwnProperty("code")) ) {
        return this.resultDataMiddlewares.success(content) 
      } else {
        return this.resultDataMiddlewares.error(action,content.error)
      }
    } catch (error) {
      throw new Error(`返回数据存在问题：${error.message}`)
    }
  }
}